

package com.maoshi.shop.user.comment.service.impl;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoshi.shop.bean.app.dto.ProductItemDto;
import com.maoshi.shop.bean.enums.OrderStatus;
import com.maoshi.shop.bean.enums.OrderType;
import com.maoshi.shop.bean.model.*;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.dao.OrderMapper;
import com.maoshi.shop.dao.OrderSettlementMapper;
import com.maoshi.shop.dao.ProductMapper;
import com.maoshi.shop.dao.SkuMapper;
import com.maoshi.shop.service.OrderItemService;
import com.maoshi.shop.service.ProductService;
import com.maoshi.shop.service.SkuService;
import com.maoshi.shop.service.UserAddrOrderService;
import com.maoshi.shop.user.comment.dto.ScoreOrderMergerDto;
import com.maoshi.shop.user.comment.service.ScoreOrderService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author LHD
 * @date 2019-12-12 13:55:57
 */
@Service
@AllArgsConstructor
public class ScoreOrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements ScoreOrderService {

    private final OrderItemService orderItemService;
    private final OrderMapper orderMapper;
    private final SkuMapper skuMapper;
    private final MapperFacade mapperFacade;
    private final SkuService skuService;
    private final ProductService productService;
    private final ProductMapper productMapper;
    private final UserAddrOrderService userAddrOrderService;
    private final Snowflake snowflake;
    private final OrderSettlementMapper orderSettlementMapper;

    @Override
    @CachePut(cacheNames = "ConfirmScoreOrderCache", key = "#userId")
    public ScoreOrderMergerDto putConfirmScoreOrderCache(String userId, ScoreOrderMergerDto scoreOrderMergerDto) {
        return scoreOrderMergerDto;
    }

    @Override
    @Cacheable(cacheNames = "ConfirmScoreOrderCache", key = "#userId")
    public ScoreOrderMergerDto getConfirmScoreOrderCache(String userId) {
        return null;
    }

    @Override
    @CacheEvict(cacheNames = "ConfirmScoreOrderCache", key = "#userId")
    public void removeConfirmScoreOrderCache(String userId) {
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order submit(String userId, ScoreOrderMergerDto mergerOrder) {
        // 提交订单
        Order scoreOrder = handlerOrder(mergerOrder);
        // 插入订单
        orderMapper.insert(scoreOrder);
        // 插入订单项，返回主键
        orderItemService.saveBatch(scoreOrder.getOrderItems());

        return scoreOrder;
    }

    private Order handlerOrder(ScoreOrderMergerDto mergerOrder){
        Date now = new Date();
        String userId = mergerOrder.getUserId();
        // 订单商品参数
        ProductItemDto productItemDto = mergerOrder.getProductItemDto();
        // 把订单地址保存到数据库
        UserAddrOrder userAddrOrder = mapperFacade.map(mergerOrder.getUserAddr(), UserAddrOrder.class);
        if (userAddrOrder == null) {
            throw new MaoshiShopBindException("请填写收货地址");
        }
        userAddrOrder.setUserId(userId);
        userAddrOrder.setCreateTime(now);
        userAddrOrderService.save(userAddrOrder);
        if(Objects.isNull(productItemDto)) {
            throw new MaoshiShopBindException("订单已经失效");
        }
        // 订单地址id
        Long addrOrderId = userAddrOrder.getAddrOrderId();
        //检查sku和prod的库存
        Sku sku = checkAndGetSku(productItemDto.getSkuId(), productItemDto);
        Product product = checkAndGetProd(productItemDto.getProdId(), productItemDto);

        // 使用雪花算法生成的订单号
        String orderNumber = String.valueOf(snowflake.nextId());
        mergerOrder.setOrderNumber(orderNumber);

        Long shopId = mergerOrder.getShopId();
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = mapperFacade.map(productItemDto, OrderItem.class);
        orderItem.setPic(StrUtil.isBlank(sku.getPic()) ? product.getPic() : sku.getPic());
        orderItem.setShopId(shopId);
        orderItem.setOrderNumber(orderNumber);
        orderItem.setUserId(userId);
        orderItem.setRecTime(now);
        orderItem.setUseScore(mergerOrder.getProductItemDto().getScorePrice());
        orderItem.setCommSts(0);
        orderItems.add(orderItem);
        // 订单信息
        Order order = new Order();
        order.setShopId(shopId);
        order.setOrderNumber(orderNumber);
        // 订单商品名称
        order.setProdName(orderItem.getProdName());
        // 用户id
        order.setUserId(userId);
        // 商品总额
        order.setTotal(mergerOrder.getTotal());
        // 实际总额
        order.setActualTotal(mergerOrder.getActualTotal());
        order.setPlatformAmount(0.0);
        order.setStatus(OrderStatus.UNPAY.value());
        order.setUpdateTime(now);
        order.setCreateTime(now);
        order.setIsPayed(0);
        order.setDeleteStatus(0);
        order.setProductNums(mergerOrder.getTotalCount());
        order.setAddrOrderId(addrOrderId);
        order.setOrderType(OrderType.SCORE.value());
        order.setReduceAmount(0.00);
        order.setFreightAmount(0.00);
        order.setRemarks(mergerOrder.getRemarks());

        order.setOrderItems(orderItems);
         //插入订单结算表
        OrderSettlement orderSettlement = new OrderSettlement();
        orderSettlement.setUserId(userId);
        orderSettlement.setIsClearing(0);
        orderSettlement.setCreateTime(now);
        orderSettlement.setOrderNumber(orderNumber);
        orderSettlement.setPayAmount(order.getActualTotal());
        orderSettlement.setPayStatus(0);
        orderSettlement.setVersion(0);
        //如果用使用积分，结算表将积分价格插入
        if(mergerOrder.getIsScorePay() != null && mergerOrder.getIsScorePay() == 1 && mergerOrder.getProductItemDto() != null){
            orderSettlement.setPayScore(mergerOrder.getProductItemDto().getScorePrice());
        }
        orderSettlementMapper.insert(orderSettlement);
        Sku updateSku = new Sku();
        updateSku.setSkuId(sku.getSkuId());
        updateSku.setStocks(orderItem.getProdCount());
        Product updateProd = new Product();
        updateProd.setProdId(sku.getProdId());
        updateProd.setTotalStocks(orderItem.getProdCount());
        // 更新sku库存
        if (skuMapper.updateStocks(updateSku) == 0) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
            productService.removeProductCacheByProdId(sku.getProdId());
            throw new MaoshiShopBindException("商品：[" + sku.getProdName() + "]库存不足");
        }
        // 更新商品库存
        if (productMapper.updateStocks(updateProd) == 0) {
            productService.removeProductCacheByProdId(product.getProdId());
            throw new MaoshiShopBindException("商品：[" + product.getProdName() + "]库存不足");
        }
//        // 更新sku库存
//        if (skuMapper.updateStocks(sku) == 0) {
//            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
//            productService.removeProductCacheByProdId(sku.getProdId());
//            throw new MaoshiShopBindException("商品：[" + sku.getProdName() + "]库存不足");
//        }
//        // 更新商品库存
//        if (productMapper.updateStocks(product) == 0) {
//            productService.removeProductCacheByProdId(product.getProdId());
//            throw new MaoshiShopBindException("商品：[" + product.getProdName() + "]库存不足");
//        }
        return order;
    }



    @SuppressWarnings({"Duplicates"})
    private Sku checkAndGetSku(Long skuId, ProductItemDto shopCartItem) {
        // 获取sku信息
        Sku sku = skuService.getSkuBySkuId(skuId);
        if (sku == null) {
            throw new MaoshiShopBindException("购物车包含无法识别的商品");
        }

        if (sku.getStatus() != 1) {
            throw new MaoshiShopBindException("商品[" + sku.getProdName() + "]已下架");
        }
        // -1为无限库存
        if (sku.getStocks() != -1 && shopCartItem.getProdCount() > sku.getStocks()) {
            throw new MaoshiShopBindException("商品：[" + sku.getProdName() + "]库存不足");
        }

        if (sku.getStocks() != -1) {
            // 这里的库存是改变的库存
            sku.setStocks(shopCartItem.getProdCount());
        }
        return sku;
    }

    @SuppressWarnings({"Duplicates"})
    private Product checkAndGetProd(Long prodId, ProductItemDto productItemDto) {
        Product product = productService.getProductByProdId(prodId);
        if (product == null) {
            throw new MaoshiShopBindException("购物车包含无法识别的商品");
        }
        if (product.getStatus() != 1) {
            throw new MaoshiShopBindException("商品[" + product.getProdName() + "]已下架");
        }
        Integer totalStocks = product.getTotalStocks();
        // 商品需要改变的库存
        if (totalStocks != -1) {
            product.setTotalStocks(productItemDto.getProdCount());
        }
        // -1为无限库存
        if (totalStocks != -1 && product.getTotalStocks() > totalStocks) {
            throw new MaoshiShopBindException("商品：[" + product.getProdName() + "]库存不足");
        }
        return product;
    }

}
